package com.timemanage.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.timemanage.dao.AppDatabase
import com.timemanage.dao.WorkDao
import com.timemanage.entity.Work
import com.timemanage.utils.AlarmReceiver
import com.timemanage.utils.AlarmService
import java.util.*

class AlarmService : Service() {

    var am: AlarmManager? = null
    var pi: PendingIntent? = null
    var time: Long? = null
    var title: String? = "没有任务目前"
    var content:String? = "赶快立个flag吧"

    override fun onCreate() {
        super.onCreate()
        Log.d("MyService", "onCreate executed")
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        getalarmTime()
        return START_REDELIVER_INTENT
    } //这里为了提高优先级，选择START_REDELIVER_INTENT 没那么容易被内存清理时杀死

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }//当提醒时间为空的时候，关闭服务，下次添加提醒时再开启//提交事件，发送给 广播接收器//这里启动的广播，下一步会教大家设置

    //这里是系统闹钟的对象
    //设置事件


    var wokdao= AppDatabase.getDatabase(MyApplication.context).WorkDao()

    fun getalarmTime(){
        var works=wokdao.selectTodo(System.currentTimeMillis())
        var minwork:Work?=null
        if(!works.isEmpty())
        for(ws in works)
        {
            if(minwork==null)minwork=ws
            else
                if(ws.startTime!! < minwork!!.startTime!!)
                    minwork=ws
        }
        title=minwork?.title
        title=minwork?.workbody
        if(minwork!=null){
          val tm=minwork.startTime!!-300000//提前五分钟
            if(tm>System.currentTimeMillis())
                time=tm
            else
                time=System.currentTimeMillis()
        }


        val startNotification = Intent(this, AlarmReceiver::class.java) //这里启动的广播
        startNotification.putExtra("title", title)
        startNotification.putExtra("content", content)
        am = getSystemService(ALARM_SERVICE) as AlarmManager //这里是系统闹钟的对象
        pi = PendingIntent.getBroadcast(
            this,
            0,
            startNotification,
            PendingIntent.FLAG_UPDATE_CURRENT
        ) //设置事件
        val any = if (time != null) {
            am!![AlarmManager.RTC_WAKEUP, time!!] = pi //提交事件，发送给 广播接收器
        } else {
            //当提醒时间为空的时候，关闭服务，下次添加提醒时再开启
            stopService(Intent(this, AlarmService::class.java))
        }

    }
}